package com.xyy.saas.payment.adpater.yop;

import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.JSONUtils;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.aggpay.AggpayClient;
import com.yeepay.yop.sdk.service.aggpay.AggpayClientBuilder;
import com.yeepay.yop.sdk.service.aggpay.model.PrePayOrderResponseDTOResult;
import com.yeepay.yop.sdk.service.aggpay.request.*;
import com.yeepay.yop.sdk.service.aggpay.response.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class YopPay {
// 该Client线程安全，请使用单例模式，多次请求共用
private final AggpayClient api = AggpayClientBuilder.builder().build();


  /**
  * 聚合支付统一下单
  */
  public PrePayOrderResponseDTOResult pay(PrePayRequest param) throws PaymentException {
      log.info("YopPay#pay param:{}", JSONUtils.toJSON(param));

      try {
          PrePayResponse response = api.prePay(param);
          log.info("YopPay#pay request:{} response:{}", JSONUtils.toJSON(param), JSONUtils.toJSON(response));
          PrePayOrderResponseDTOResult result = response.getResult();

          if(!Constants.YOP_PAY_SUCCESS_CODE.equals(result.getCode())) {
              throw new PaymentException(result.getCode(), result.getMessage());
          }

          return result;
      }
      catch(Exception ex) {
          log.error("YopPay#pay error, param=" + JSONUtils.toJSON(param) + ", errorMsg=" + ex.getMessage() ,ex);

          if(ex instanceof PaymentException) {
            throw ex;
          }
          else if(ex instanceof YopClientException) {
            throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR.getCode(), ex.getMessage());
          }

          throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR);
      }
  }
}